// portal.cpp : Contains the definition of the portal component, which allows transportation of objects
// to other areas within the world
//$Id: Portal.cpp 28 2009-08-27 20:06:05Z brwarner2 $
#include "stdafx.h"
#include "Portal.h"
#include "GameMonkey.h"
#include "ObjectManager.h"
#include "gmArea.h"
#include "gmVector.h"
#include "Entity.h"
#include "Area.h"

int CPortal::GMCall(gmThread* a_thread, const std::string &name)
{
	if( name == "Teleport" )
	{
		CObjectManager* pOM = GetGlobalObjectManager(*a_thread->GetMachine());
		GM_CHECK_NUM_PARAMS(3);
		GM_CHECK_TABLE_PARAM( obj, 0 );
		using namespace gmArea;
		gmAreaObject* pArea = reinterpret_cast<gmAreaObject*>( a_thread->ParamUser(1, &gmArea::GM_AREA) );
		GM_CHECK_TABLE_PARAM( vec, 2 );
		bug::math::CVector pos = GetVector( *a_thread->GetMachine(), vec );
		
		//Get the objets current area
		ObjectID id = obj->Get(a_thread->GetMachine(), "ObjectID").GetIntSafe();
		CEntity* pEnt = reinterpret_cast<CEntity*>(pOM->GetComponent(id, CEntity::COMPONENT_ID));
		CArea* pSource = pEnt->GetArea();

		//Get new area
		CArea* pDest = pArea->pArea;

		//Change the objects ownership
		pSource->RegisterTransport(id, pDest, pos);

		//Get the area object
		return GM_OK;
	}
	return GM_EXCEPTION;
}

void CPortal::RegisterGM(gmMachine *pGM)
{
	//Get the object manager
	CObjectManager* pOM = GetGlobalObjectManager(*pGM);
	pOM->RegisterMemberFunction(COMPONENT_ID, "Teleport");
}